/**
 * 公共事务方法
 */

const sequelize = require('../utils/db.js')
const {getVal, error, success} = require('../utils/index.js')

module.exports = {

    /**
     * 查询
     */
    async findAll(table, where = '') {
        try {
            const data = await sequelize.query(`SELECT * FROM ${table} ${where}`)
            return success(data[0])
        } catch (err) {
            return error()
        }
    },

    /**
     * 创建
     */
    async create(table, body) {
        try {
            let values = ''
            if (Array.isArray(body)) {
                body.map(item => {
                    values += `(null, ${getVal(item)}),`
                })
            } else {
                values = `(null, ${getVal(body)})`
            }
            let newValues = values.replace(/\,$/, '')
            const data = await sequelize.query(`INSERT INTO ${table} values ${newValues}`)
            return success(data[1])

        } catch (err) {
            return error()
        }
    },

    /**
     * 删除
     */
    async delete(table, where) {
        try {
            const data = await sequelize.query(`DELETE FROM ${table} where ${where}`)
            return success(data[0]['affectedRows'])
        } catch (err) {
            return error()
        }
    },

    /**
     * 更新
     */
     async update(table, params, where) {
        try {
            const data = await sequelize.query(`UPDATE ${table} SET ${params} where ${where}`)
            return success(data[0]['affectedRows'])
        } catch (err) {
            return error()
        }
    },

}